import { nextTick, Ref, ref } from 'vue'
import { appConfig } from '../config/app';


export function useLoading(fn: (...args: any[]) => Promise<any>, immediate = false, resetTime = appConfig.button.resetTime): [() => Promise<void>, Ref<boolean>] & { onLoad: () => Promise<void>, loading: Ref<boolean> } {
  const loading = ref(false)
  const onLoad: () => Promise<void> = async (...val: any): Promise<void> => {
    if (loading.value) return
    try {
      loading.value = true
      return await fn(...val)
    } finally {
      if (resetTime <= 0) {
        loading.value = false
      } else {
        setTimeout(() => {
          loading.value = false
        }, resetTime);
      }
    }
  }
  immediate && nextTick(() => onLoad())
  return Object.assign([onLoad, loading] as [() => Promise<void>, Ref<boolean>], { onLoad, loading });
}
